package wf3.filter;

import acceso.util.Escritor;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import wf3.core.Configuration;

/**
 *
 * @author Rómulo Galindo Tanta
 */
public class GatewayFilter implements Filter {

    FilterConfig filterConfig = null;
    static boolean filter;
    static String host;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        Escritor.escribe_debug("[filtro: GatewayFilter] [path: " + req.getRequestURI() + (req.getQueryString() != null ? "?" + req.getQueryString() : "") + "]");

        if (filter) {
            if (req.getHeader("HOST").contentEquals(host)) {
                chain.doFilter(request, response);
                return;
            }

            String uri = req.getRequestURI();
            uri = uri + (req.getQueryString() == null ? "" : "?" + req.getQueryString());
            Escritor.escribe_info("redireccionando a :http://" + host + uri);
            res.sendRedirect("http://" + host + uri);
            return;
        }

        chain.doFilter(request, response);
    }

    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) {
        Escritor.escribe_debug("Iniciando Filtro(GatewayFilter)");
        this.filterConfig = filterConfig;
        filter = ((Configuration) filterConfig.getServletContext().getAttribute("CFG")).isWf_filter();
        Escritor.escribe_debug("Filtro(GatewayFilter) con filter=" + filter);
        host = ((Configuration) filterConfig.getServletContext().getAttribute("CFG")).getWf_filter_host();
        Escritor.escribe_debug("Filtro(GatewayFilter) con host=" + host);
        Escritor.escribe_info("Filtro (GatewayFilter) Iniciado");
    }

    public synchronized static void update_filter(boolean f, String h) {
        Escritor.escribe_debug("Actualizando Filtro(GatewayFilter)");
        filter = f;
        Escritor.escribe_debug("Filtro(GatewayFilter) actualizando filter=" + filter);
        host = h;
        Escritor.escribe_debug("Filtro(GatewayFilter) actualizando host=" + host);
        Escritor.escribe_info("Filtro (GatewayFilter) Actualizado");
    }

}
